//
//  CameraScanVModel.swift
//  Scaner
//
//  Created by liyahao on 2025/4/8.
//

import Foundation
import VisionKit
import Combine

final class CameraScanVModel: NSObject, ObservableObject {
    @Published var errorMessage: String?
    @Published var imageArray: [UIImage] = []
    
    func getDocumentCameraViewController() -> VNDocumentCameraViewController {
        let vc = VNDocumentCameraViewController()
        vc.delegate = self
        return vc
    }
    
    func removeImage(image: UIImage) {
        imageArray.removeAll{ $0 == image }
    }
}

extension CameraScanVModel: VNDocumentCameraViewControllerDelegate {
    func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
    
    func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFailWithError error: Error) {
        errorMessage = error.localizedDescription
    }
    
    func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {
        for i in 0..<scan.pageCount {
            let image = scan.imageOfPage(at:i)
            
            let captureOcr = CameraScanOCR(image: image, setScanTitle: i == 0)
            captureOcr.performOcr()
        }
        saveContext()
        controller.dismiss(animated: true, completion: nil)
    }
    
    func saveContext() {
        
    }
}
